package controller.backstage;

import com.google.gson.Gson;
import model.Query;
import model.Result;
import model.InnerResult;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.HttpUtils;
import utils.ModelUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.function.Function;

import static model.InnerResult.Status.FULFILLED;

@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private final Gson GSON = new Gson();
    private final String URI_PREFIX = "/api/admin/user/";
    private final Function<InnerResult, Result> FILLER = dto -> {
        if (dto.getStatus() == FULFILLED) {
            return Result.fulfill(dto.getObject());
        } else {
            return Result.reject(dto.getObject().toString());
        }
    };

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        String action = req.getRequestURI().replace(URI_PREFIX, "");

        try {
            switch (action) {
                case "allUser":
                    allUser(req, resp, GSON);
                    break;
                case "deleteUser":
                    deleteUser(req, resp, GSON);
                    break;
                case "searchUser":
                    searchUser(req, resp, GSON);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void searchUser(HttpServletRequest req, HttpServletResponse resp, Gson gson) throws IOException {
        Query query = HttpUtils.getQuery(req);
        InnerResult dto = userService.searchUser(query);
        resp.getWriter().print(gson.toJson(FILLER.apply(dto)));
    }

    private void deleteUser(HttpServletRequest req, HttpServletResponse resp, Gson gson) throws IOException {
        Query query = HttpUtils.getQuery(req);
        if (ModelUtils.isInvalid(query)) {
            resp.getWriter().print(gson.toJson(Result.reject("非法参数")));
            return;
        }

        InnerResult dto = userService.deleteUser(query);
        resp.getWriter().print(gson.toJson(FILLER.apply(dto)));
    }

    private void allUser(HttpServletRequest req, HttpServletResponse resp, Gson gson) throws IOException {
        InnerResult dto = userService.getAllUsers();
        resp.getWriter().print(gson.toJson(FILLER.apply(dto)));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {

    }
}
